/**
 * APP GEN: 51DESK.Quark -> NodeJS + Express
 *
 * Usage:
 *     node server.js
 * Site:
 *     localhost:10101 or localhost:process.env.PORT
 */

// Public APP Global components
var express = require("express"),
    bodyParser = require("body-parser"),
    session = require('express-session');


// GEN APP
var app = express();

// SET: HTTP APP Socket Listen Port
app.set('port', process.env.PORT || 10101);

app.use(express.static(__dirname + '/build'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));


var router = express.Router();

router.get("/", function (req, res) {
    res.location("index");
})

app.use("/", router);

app.use(function (req, res, next) {
    res.set({
        "Content-type": "application/json",
        "Access-Control-Allow-Origin": "*"
    });

    var requrl = req.url;

    if (requrl.indexOf("api") > -1) {
        if (!req.session.user) {
            res.send({
                status: 1,
                errcode: 6000,
                errmsg: "APP Server Error..."
            });
        }
        else {
            next();
        }
    }
    else {
        res.redirect('/#' + requrl);
    }
});


app.listen(app.get('port'), function () {
    console.log("APP Server is running at 127.0.0.1:" + app.get('port') + '...');
});
